package com.ruoyi.system.service.impl.video;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.translate.TransApi;
import com.ruoyi.common.utils.translate.TranslateUtil;
import com.ruoyi.system.domain.config.VsConfig;
import com.ruoyi.system.domain.config.VsTranslateApi;
import com.ruoyi.system.domain.video.VsLang;
import com.ruoyi.system.domain.video.VsLangInit;
import com.ruoyi.system.mapper.config.VsConfigMapper;
import com.ruoyi.system.mapper.config.VsTranslateApiMapper;
import com.ruoyi.system.mapper.video.VsLangInitMapper;
import com.ruoyi.system.mapper.video.VsLangMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.video.VsLangTranslateMapper;
import com.ruoyi.system.domain.video.VsLangTranslate;
import com.ruoyi.system.service.video.IVsLangTranslateService;

/**
 * 语言对照Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-17
 */
@Service
public class VsLangTranslateServiceImpl implements IVsLangTranslateService 
{
    @Autowired
    private VsLangTranslateMapper vsLangTranslateMapper;

    @Autowired
    private VsLangInitMapper vsLangInitMapper;

    @Autowired
    private VsLangMapper vsLangMapper;

    @Autowired
    private VsConfigMapper vsConfigMapper;

    @Autowired
    private VsTranslateApiMapper vsTranslateApiMapper;

    /**
     * 查询语言对照
     * 
     * @param id 语言对照主键
     * @return 语言对照
     */
    @Override
    public VsLangTranslate selectVsLangTranslateById(Long id)
    {
        return vsLangTranslateMapper.selectVsLangTranslateById(id);
    }

    /**
     * 查询语言对照列表
     * 
     * @param vsLangTranslate 语言对照
     * @return 语言对照
     */
    @Override
    public List<VsLangTranslate> selectVsLangTranslateList(VsLangTranslate vsLangTranslate)
    {
        return vsLangTranslateMapper.selectVsLangTranslateList(vsLangTranslate);
    }

    /**
     * 新增语言对照
     * 
     * @param vsLangTranslate 语言对照
     * @return 结果
     */
    @Override
    public int insertVsLangTranslate(VsLangTranslate vsLangTranslate)
    {
        return addInfo(vsLangTranslate);
    }

    private int addInfo(VsLangTranslate vsLangTranslate) {
        // 先把要新增的键值插入到初始化里
        VsLangInit vsLangInit = new VsLangInit();
        vsLangInit.setKeyCode(vsLangTranslate.getKeyCode());
        vsLangInit.setChinese(vsLangTranslate.getLanguage());
        int langInitByParams = vsLangInitMapper.insertVsLangInit(vsLangInit);
        return langInitByParams;
    }

    /**
     * 修改语言对照
     * 
     * @param vsLangTranslate 语言对照
     * @return 结果
     */
    @Override
    public int updateVsLangTranslate(VsLangTranslate vsLangTranslate)
    {
        return editInfo(vsLangTranslate);
    }

    private int editInfo(VsLangTranslate vsLangTranslate) {
        // 先把初始化里的值更新
        VsLangInit vsLangInit = new VsLangInit();
        vsLangInit.setKeyCode(vsLangTranslate.getKeyCode());
        vsLangInit.setChinese(vsLangTranslate.getLanguage());
        int langInitByParams = vsLangInitMapper.updateVsLangInitByParams(vsLangInit);
        return langInitByParams;
    }

    /**
     * 批量删除语言对照
     * 
     * @param ids 需要删除的语言对照主键
     * @return 结果
     */
    @Override
    public int deleteVsLangTranslateByIds(Long[] ids)
    {
        return vsLangTranslateMapper.deleteVsLangTranslateByIds(ids);
    }

    /**
     * 删除语言对照信息
     * 
     * @param id 语言对照主键
     * @return 结果
     */
    @Override
    public int deleteVsLangTranslateById(Long id)
    {
        return vsLangTranslateMapper.deleteVsLangTranslateById(id);
    }

    @Override
    public int batchInsertVsLangTranslate(List<VsLangTranslate> list) {
        return vsLangTranslateMapper.batchUpdateVsLangTranslate(list);
    }

    @Override
    public List<VsLangTranslate> batchTranslate(List<VsLangTranslate> list) {
        // 如果要翻译的语言是英文直接分割一下键值返回，不需要再去请求英文翻译英文
        String languageType = list.get(0).getLanguageType();
        if ("zh".equals(languageType)) {
            for (VsLangTranslate v : list) {
                if (!"".equals(v.getLanguage()) && v.getLanguage() != null) {
                    continue; // 如果language不为空或非null，则跳过此循环体
                }
                // 将键值中的点替换为空格并将他们用换行符连接
                v.setLanguage(v.getChinese());
            }
            return list;
        }
        List<VsTranslateApi> apiList = vsTranslateApiMapper.selectVsTranslateApiList(new VsTranslateApi());
        if (apiList.isEmpty()) {
            return list;
        }
        int num = 0;
        for (VsTranslateApi a : apiList) {
            if (languageType.equals(a.getLangType())) {
                num++;
            }
        }
        if (num == 0) {
            throw new IllegalArgumentException("翻译api列表中未找到该语言");
        }
        VsConfig config = new VsConfig();
        config.setGroup("basic");
        List<VsConfig> configList = vsConfigMapper.selectVsConfigList(config);
        String appid = null;
        String sec_key = null;
        for (VsConfig v : configList) {
            if ("app_id".equals(v.getName())) {
                appid = v.getValue();
            }
            if ("sec_key".equals(v.getName())) {
                sec_key = v.getValue();
            }
        }
        TransApi api = new TransApi(appid,sec_key);
        TranslateUtil util = new TranslateUtil();
        String result = "";
        StringBuilder keyCodeBuilder = new StringBuilder();
        for (VsLangTranslate v : list) {
            if (!"".equals(v.getLanguage()) && v.getLanguage() != null) {
                continue; // 如果language不为空或非null，则跳过此循环体
            }
            keyCodeBuilder.append(v.getChinese()).append("\n");
        }
        if (keyCodeBuilder.length() > 0) {
            String allKeyCodes = keyCodeBuilder.toString();
            result = api.getTransResult(allKeyCodes, "auto", languageType);
            List<String> conversion = util.batchConversion(result);
            if (conversion.size() == list.size()) {
                for (int i = 0; i < conversion.size(); i++) {
                    list.get(i).setLanguage(conversion.get(i));
                }
            }
        }
        return list;
    }

    private String removeFirstDotAndReplaceOthers(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        // 移除第一个点及之前的字符
        int firstDotIndex = str.indexOf('.');
        if (firstDotIndex != -1) {
            str = str.substring(firstDotIndex + 1);
        }

        // 将剩余字符串中的点替换为空格
        str = str.replace(".", " ");

        return str.trim(); // 可选：移除首尾空白字符
    }

    public static List<List<VsLangTranslate>> splitList(List<VsLangTranslate> originalList, int maxSize) {
        List<List<VsLangTranslate>> result = new ArrayList<>();
        for (int i = 0; i < originalList.size(); i += maxSize) {
            result.add(new ArrayList<>(originalList.subList(i, Math.min(i + maxSize, originalList.size()))));
        }
        return result;
    }

}
